#!/bin/bash
#=======================
# Author : Ali Moradzade
# Created: 2022/01/15
#=======================

#09 convert json bookmark

function usage {
	echo "Usage: $1 [input-json-file-name] [output-pdftk-bookmark-file]"
}

function checkinput {
	local input_file_name=$1
	if ! [ -f "$input_file_name" ]
	then
		echo "json file: $input_file_name, does not exist. aborting ..."
		exit
	fi
}

function checkoutfile {
	local output_file_name=$1
	if [ -f "$output_file_name" ]
	then
		echo "$output_file_name exists."
		read -n 1 -p "do you want to overwrite it? (Y/n) "
		echo
		case "$REPLY" in
			Y)
				echo "overwriting $output_file_name ..."
				echo -n "" > $output_file_name
				;;
			*)
				echo "aborting ..."
				exit
			;;
		esac
	fi
}

if [ "$#" -ne 2 ]
then
	usage $(basename $0)
	exit
fi

checkinput $1
checkoutfile $2

input_file_name=$1
output_file_name=$2

echo "process started ..."
jq '.[] | .title, .page, .level' $input_file_name |
	while read title; read page; read level
do
	page=$(echo "$page"   | sed -e 's/^"//; s/"$//')
	title=$(echo "$title" | sed -e 's/^"//; s/"$//')
	level=$(echo "$level" | sed -e 's/^"//; s/"$//')

	echo "BookmarkBegin"
	echo "BookmarkTitle:" "$title"
	echo "BookmarkLevel:" "$level"
	echo "BookmarkPageNumber:" "$page"
done >> $output_file_name

echo
echo "process finished successfully"
echo "your output json file is in: $output_file_name"
